<template>
	<div class="container">
		<header class="customHeaderStyle">
			<!-- <router-link :to="'/main/profile'"> -->
			<div class="go-back" @click="turn">
				<i></i>
				<i></i>
				<i></i>
			</div>
			<!-- </router-link>	 -->
			<div class="headerCustomTitle">向商家付款</div>
		</header>
		<div style="height:3rem;"></div>
		<div class="wrapper">
			<div class="inner">
				<!-- <canvas id="ean"></canvas> -->
				<qr-code id="qr" :text="message"></qr-code>
				<div class="pay_method">
					<i class="icon njfont nj-jinrong"></i>
					<div class="tip_1">使用钱包余额</div>
				</div>

			</div>
			<div class="tip_2">每分钟自动更新付款码</div>
		</div>
		<child ref="pro" @WxhpasswordPendingChange="handle"></child>
	</div>
</template>
<script>
	import { mapMutations, mapActions, mapGetters } from "vuex";
	import VueQRCodeComponent from 'vue-qrcode-component'
	import Ean from '../../utils/WXH/ean13.js'
	import { Toast } from '../../utils/toast.js'
	import MD5 from '../../utils/md5_wxh.js'
	import child from '../../real-components/ConfirmOrder/ConfirmOrderPursekey'
	import test from './index.vue'
	import { MessageBox } from '../../ui-components'

	export default {
		data() {
			return {
				message: '', //二维码数据
				password: '',
				webSocket: '',
				result: '',
        timer: 0,
        interval: '',
        flag: true
			}
		},
		computed: {
			...mapGetters('wxh', [
				'sessionId',
				'userInfo',
				'login'
			])
		},
		components: {
			'qr-code': VueQRCodeComponent,
			child,
			test
		},
		mounted() {

		},
		async created() {
			await this.getUserInfo();
			await this.initData();
			await this.socket();
		},
    beforeDestroy(){clearInterval(this.interval)},
    watch:{
      timer:function (newVal, oldVal) {
        //超过9秒,断开重连;
		    if(newVal == 3){
		      clearInterval(this.interval);
          this.webSocket.close();
          this.timer = 0;
          this.flag = false;
          this.socket();
        }
      }
    },
		methods: {
			...mapActions('wxh', [
				'getUserInfo'
			]),
			...mapMutations('wxh', [
				'USER_INFO',
				'ClEAR_SESSIONID',
				'LOGO_OUT',
				'LOGO_IN',
				'CLEAR_INFO'
			]),
			async initData() {
				await this.reFreshUserInfo(this);
				let info = {
					userId: this.userInfo.userid,
					phone: this.userInfo.mobile,
					vipname: this.userInfo.vipname,
					remainingscore: this.userInfo.remainingscore,
					sessionId:this.sessionId,
				}
				//二维码
				this.message = JSON.stringify(info);
				//条形码
				// let el = document.getElementById('ean');
				// let ea = new Ean(el, '1234566444644');

			},
			turn() {
				if(this.$route.query.Page) {
					this.$router.go(-1);
				} else {
					this.$router.push({
						name: 'profile'
					});
				}

			},

			socket() {
				this.webSocket = new WebSocket(`ws://${api.websocket_host}`);
			  let id = this.userInfo.userid;
			  let that = this;
        if(this.webSocket.readyState === 0 && id) {
          this.webSocket.onopen = function() {
            let a = {
              "command": "login",
              "data": {
                "userId": id,
                "enterpriseCode": api.enterpriseCode,
								"sessionId":that.sessionId,
              }
            };
            let heart = {
              "command":"heart",
              "data":{
                "beat": "1",
                "enterpriseCode": api.enterpriseCode
              }
            };

            that.webSocket.send(JSON.stringify(a));
            that.interval = setInterval(()=>{
              that.timer += 1;
              that.webSocket.send(JSON.stringify(heart));
            },3000);

          };
          that.webSocket.onmessage = function(res) {
            let result = JSON.parse(res.data);
            that.result = result;
            if(result.command == "login") {
              // if(result.returnCode == 1 && that.flag) {
              //   Toast({
              //     message: '扫码成功！',
              //     type: 'success',
              //     duration: api.alertTime_2
              //   })
              // }
            }

            if(result.command == "inputPassword") {
              if(result.returnCode == 1) {
                if(that.userInfo.walletStatus == 0) {
                  MessageBox.confirm('是否前往设置钱包支付密码')
                    .then(action => {
                      // console.log('action', action);
                      // that.$router.push('/main/SetKeyWallet');
                      that.$router.push({name: "SetKeyWallet"});
                    })
                    .catch(error => {
                      console.log(error);
                    })

                } else {
                  that.$refs.pro.showOrHide();
                }

              }
            }

            if(result.command == "checkPassword") {
              if(result.returnCode == 1) {
                let a;
                switch(result.data[0].payStatus) {
                  case 2:
                    a = '支付成功';
                    that.webSocket.close();
                    break;
                  case 3:
                    a = '支付失败';
                    that.webSocket.close();
                    break;
                  case 5:
                    a = '密码错误';
                    that.$refs.pro.showOrHide();
                    break;

                }
                Toast({
                  message: a,
                  type: 'success',
                  duration: api.alertTime_2
                })
              } else {
                Toast({
                  message: "支付异常！",
                  type: 'fail',
                  duration: api.alertTime_2
                })
              }
            }

            if(result.command == "heart"){
              that.timer = 0;
            }
          };
          that.webSocket.onerror = function(error) {
            Toast({
              message: error,
              type: 'fail',
              duration: 3000
            })
          }
        }
			},
      handle(data) {
        if(data.result) {
          Toast({
            message: data.msg,
            type: 'success',
            duration: api.alertTime_2
          })
          this.password = data.keyall;
          this.sendPassword();
          return
        }else if(!data.response){
          let that = this;
          this.webSocket.close();

          this.webSocket.onclose = function () {
            let status = {
              command: "connectStatus",
              data:{
                status:false,
                msg:"用户输入超时，webSocket连接关闭！"
              }
            }
            that.webSocket.send(JSON.stringify(status));
          }
          return
        } else {
          Toast({
            message: data.msg,
            type: 'fail',
            duration: api.alertTime_2
          })
          return
        }
      },
      sendPassword() {
        let id = this.userInfo.userid;
        let b = {
          "command": "checkPassword",
          "data": {
            "userId": id,
            "enterpriseCode": this.result.data[0].enterpriseCode,
            "walletPassword": MD5(this.password),
            "storeOrderNo": this.result.data[0].storeOrderNo,
            "sessionId":this.sessionId
          }
        }
        this.webSocket.send(JSON.stringify(b));
      },
		}
	}
</script>

<style scoped>
.customHeaderStyle{
		position: relative;
		background: #fff;
		min-height: 3rem;
		border-bottom: 1px solid #eaeaea;
		color: #444;
		font-weight: 700;
		left: 0;
		top: 0;
		line-height: 2.25rem;
		/* z-index: 2; */
		width: 100%;
		font-size: .9rem;
		text-align: center;
		margin: 0;
		padding: 0;
	}
	.headerCustomTitle{
		overflow: hidden;
		right: 6rem;
		font-weight: 500;
		min-height: 2.25rem;
		position: absolute;
		margin: 0;
		text-align: left;
		white-space: nowrap;
		left: 3rem;
		width: auto;
		text-overflow: ellipsis;
		z-index: 2;
		font-size: 1.1rem;
		margin-top: .35rem;
		top: 1px;
	}
	#app {
		background: #fff;
	}

	.container {
		height: 100%;
		background: rgba(41, 154, 40, 1);
	}

	.wrapper {
		position: relative;
		width: 100%;
		/* height: 100%; */
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		align-items: center;
		/* top: 10%; */
		height: 90%;
	}

	.inner {
		background: #fff;
		width: 90%;
		/*margin: auto;*/
		/*margin-top: 2rem;*/
		position: relative;
		/*top: 10%;*/
		/*transform: translateY(-80%);*/
	}

	#qr {
		width: 100%;
		height: 100%;
		margin: auto;
		padding-top: 2rem;
		display: flex;
		justify-content: space-around;
	}

	#qr img {
		height: 50%;
		width: 60%;
	}

	#ean {
		margin-top: 2rem;
	}

	.pay_method {
		height: 2.5rem;
		margin-top: 1rem;
		font-size: 0.8rem;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tip_2 {
		/*margin-top: 9rem;*/
		color: #fff;
	}

	.njfont {
		margin-right: 0.3rem;
		font-size: 1.2rem;
		color: #f4b419;
	}
</style>
